package com.mygame.Svetofor.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mygame.Svetofor.Profile;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Andrey
 */
public class ProfileSQL extends SQLiteOpenHelper{

    final static int DB_VER = 1;
    final String TABLE_NAME = "Profiles";
    final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
                                "( _id INTEGER PRIMARY KEY, " +
                                " name VARCHAR(100), " +
                                "dificulity INTEGER, " +
                                "theme INTEGER, " +
                                "score INTEGER, " +
                                "level INTEGER)";
    final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
    final static String DB_NAME = "SvetoforDB.db";

    Context mContext;

    public ProfileSQL(Context context) {
        super(context, DB_NAME, null, DB_VER);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE);
        onCreate(db);
    }

    public ArrayList<Profile> getProfiles() {
        ArrayList<Profile> result = new ArrayList<Profile>();
        Profile p;

        SQLiteDatabase database = getReadableDatabase();
        Cursor cursor = database.
          rawQuery("select * from " + TABLE_NAME, null);
        cursor.moveToFirst();
        try {
            for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
                p = new Profile();
                p.setId(cursor.getInt(cursor.getColumnIndex("_id")));
                p.setName(cursor.getString(cursor.getColumnIndex("name")));
                p.setDificulity(cursor.getInt(cursor.getColumnIndex("dificulity")));
                p.setTheme(cursor.getInt(cursor.getColumnIndex("theme")));
                p.setScore(cursor.getInt(cursor.getColumnIndex("score")));
                p.setLevel(cursor.getInt(cursor.getColumnIndex("level")));
                result.add(p);
            }
            cursor.close();
        } finally {
            database.close();
        }

        return result;
    }

    public void delete(Profile profile){
        try {
            SQLiteDatabase database = this.getWritableDatabase();
            if (database.isOpen()){
                database = getWritableDatabase();
                database.delete(TABLE_NAME, "_id=?", new String[] { String.valueOf(profile.getId()) });
            }
       } catch (Exception e) {
         // TODO: handle exception
       }finally{
         close();
       }
    }

    public boolean setProfile(Profile profile) {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues myValues = new ContentValues();
        String[] Values = new String[1];
        String Where = "";
        int rowsAffected = 0;

        try{
            database = this.getWritableDatabase();

            if (database.isOpen()){

                database.beginTransaction();

                myValues = new ContentValues();

                myValues.put("_id", profile.getId());
                myValues.put("name", profile.getName());
                myValues.put("dificulity", profile.getDificulity());
                myValues.put("theme", profile.getTheme1());
                myValues.put("score", profile.getScore());
                myValues.put("level", profile.getLevel());

                Values[0] = String.valueOf(profile.getId());

                Where = "_id= ?";

                rowsAffected = database.update(TABLE_NAME, myValues, Where , Values);

                // Check to see if anything was really updated
                if (rowsAffected == 0){
                    //Insert row since it doesn't truly exist.
                    database.insert(TABLE_NAME, "", myValues);
                }

                database.setTransactionSuccessful();

                database.endTransaction();

                return true;
            }
            else{
                return true;
            }
        }
        catch(SQLiteException e){
            Log.e(DB_NAME, e.getMessage());
            return false;
        }
        finally{
            database.close();
        }
    }
}
